<?php

	/**
	 * SynergyActionMap.php (Singleton)
	 *
	 * This class holds the hash map of actions that are accessed
	 * by request.
	 **/

	class SynergyActionMap {

		private static $_instance	= null;
		private $_map		 		= null;

		/**
		 * Constructor attempts to restore the map from cache
		 * before resorting to reparsing the XML definition.
		 **/
		private function __construct() {
	
			$this->_map = $this->_buildFromXML();

		}

		/**
		 * Prevent _clone(...) from being called.
		 **/
		private function __clone() {}

		public static function getInstance() {

			if(!self::$_instance) {
				self::$_instance = new SynergyActionMap();
			}

			return self::$_instance;

		}

		/**
		 * Parses XML definition of actions.
		 **/
		private function _buildFromXML() {

			$config	= SynergyConfiguration::getInstance();
			$file	= $config->get("routes.file"); 

			if(!file_exists(BASE_PATH . $file)) {
				error_log("[SYNERGY - ERROR] : "
					. "Configuration file not found "
					. "(" . BASE_PATH . $file  . ")");
				exit;
			}

			$xmlContent = file_get_contents(BASE_PATH . $file);

			try {
				$xmlObj = new SimpleXMLElement($xmlContent);
			} catch(Exception $e) {
				error_log("[SYNERGY - ERROR] : Failed to process XML");
			}

			$this->_processXML($xmlObj);

		}
		
		/**
		 * Recursive function to process and store configurations.
         **/
        private function _processXML($xml) {

			foreach($xml->children() as $type => $package) {
				if($type != 'package') continue;
				$this->_createPackage($package,$package['namespace']);
			}

		}

		/**
		 * Create action and store in the map
		 **/
		private function _createPackage($package,$prefix) {
			
			foreach($package as $type => $node) {
				if($type == 'package') {
					$this->_createPackage($node,$prefix.$node['namespace']);
				} else {
					echo "~ ".$prefix.'/'.$node['name'].'<br />';
				}
			} 

		}

	}

?>
